
<%
if (session.getAttribute("username") == null) {
	%><jsp:forward page="login.jsp" /><%
}%>

<%@ page import = "java.sql.*, connection.*"%>  
<%
String listname = (String)request.getParameter("listname");
String username = (String)session.getAttribute("username");
String assign = (String)request.getParameter("assignpoll");
DbConnection db = new DbConnection();
String chequesql = "SELECT LName, MasterUsername from ParticipantList WHERE LName = '"+listname+"' AND MasterUsername = '"+username+"'";
String state = "";
if(assign == null){
		try{
			if(db.getConn().prepareStatement(chequesql).executeQuery().next()){
				System.out.println("Insert failed: already exists!");
				state = "add,fail";
			}else{
				String sql = "INSERT into ParticipantList(isTemplate, LName, MasterUsername) VALUES(0, '"+listname+"', '"+username+"')";
				System.out.println("SQL2:"+sql);
				db.getConn().prepareStatement(sql).executeQuery();
				db.close();
				state = "add,success";
				//response.sendRedirect("/DBP/success.jsp?pmAddList=true&listadd="+listname);
			}
		}catch(SQLException e){
			System.out.println("Insert failed: already exists!");
			state = "add,fail";
			//response.sendRedirect("/DBP/success.jsp?pmAddList=false");
		}
}else{
	String pid = (String)request.getParameter("pollid");
	if(pid != null){
		System.out.println("pid:"+pid);
		try{
			String sql = "UPDATE ParticipantList SET Pollid="+pid+", PVersion="+pid+" WHERE LName='"+listname+"' AND MasterUsername='"+username+"'";
			System.out.println("SQL:"+sql);
			Connection conn = db.getConn();
			System.out.println("");
			PreparedStatement pss = conn.prepareStatement(sql);
			ResultSet rs = pss.executeQuery();
			//response.sendRedirect("/DBP/success.jsp?pmAddList=true&listpollassigned=true");
			state = "update,success";
		}catch(Exception e){
			System.out.println(e.toString());
			//response.sendRedirect("/DBP/success.jsp");
			state = "update,fail";
		}
	}
}
System.out.println("************OVER HERE*****************");
if(state.equals("add,success")){
	response.sendRedirect("/DBP/success.jsp?pmAddList=true&listadd="+listname);
}else if(state.equals("add,fail")){
	response.sendRedirect("/DBP/success.jsp?pmAddList=false");
}else if(state.equals("update,success")){
	System.out.println("assigned poll!poll is :"+listname);
	response.sendRedirect("/DBP/success.jsp?listpollassigned=true&assignedpoll="+listname);
}else {
	response.sendRedirect("/DBP/success.jsp?listpollassigned=false");
}


%>